package Servlet.Add;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@WebServlet("/novelImageUpload")
public class novelImageUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");		
		//java.io.PrintWriter out = response.getWriter();	
		String msg = "";
		String novelNumber = "";
		String novelImage = "";
		String action = "";
		String url = "novelImageUpload.jsp";
		
		try {
			novelNumber = request.getParameter("novelNumber");
			novelImage   = request.getParameter("image");
			
			String path = request.getServletContext().getRealPath("") ; //当前项目运行时所在的物理目录
			String uploadFolder = "novelImage/";					//存放文件的子目录
			path += uploadFolder; 												//文件存放的目录
			
			for (int f = 0; f < 1; f++) {
				msg = "（无图片）";
				
				if (novelImage == null) {
					novelImage = "";
					break;
				}
				
				if (novelImage.trim().equals("")) {
					novelImage = "";
					break;
				}
				
				File file = new File(path, novelImage); 								//创建File对象
				
				if (file.exists() == false) {									//如果不存在
					novelImage = "";
					break;
				}
				
				if (file.isDirectory()) {										//如果是文件夹
					if (file.delete() == false) {
						msg += "删除同名的文件夹失败。";
						novelImage = "";
						break;
					}
				}

				uploadFolder = uploadFolder.replace("\\", "/");					// 将\替换为/
				String urlImage = uploadFolder + novelImage + "?t=" + (new Date()).getTime();	//加上时间参数以显示最新图片
				
				msg = "<a href='" + urlImage + "' target='_blank'><img src='" + urlImage + "' height='100'></a>"; 
				msg += "<div style='margin-top:60px;'>&emsp;&emsp;&emsp;&emsp;";
				msg += "&emsp;&emsp;（<a href='novelInfoServlet?novelNumber=" + novelNumber + "' target='_top'>商品详情</a>";

			}
			
		} catch (Exception e) {
			msg += "系统发生错误。";	
			e.printStackTrace();
		} finally {			
			request.setAttribute("msg", msg);	
			
			action  = "novelImageUploadDo?novelNumber=" + novelNumber + "&novelImage=" + novelImage;
			request.setAttribute("action", action);

			if (novelNumber.length() > 30) {
				request.getSession().setAttribute("novelImage" + novelNumber, novelImage);		//保存到session
			}
			
			request.getRequestDispatcher(url).forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
